package com.wuchao.ehcache.service;

import com.wuchao.ehcache.dao.UserRepository;
import com.wuchao.ehcache.entity.User;
import com.wuchao.ehcache.utils.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author WuChao
 * @version 1.0
 * @date 2020/4/21 18:40
 */
@Service
@Slf4j
@CacheConfig(cacheNames = {"users_test"})
public class UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CacheUtil cacheUtil;

    private static final String CACHE_KEY = "'person'";//这里一定要加单引号,否则会被当做一个正常的字符串来识别

    private static final String CACHE_NAME = "users";//对应ehcache.xml中cache的name



//    @Cacheable(value = CACHE_NAME,key = "#id")
    public User get(Integer id) throws ClassNotFoundException {
        User user = cacheUtil.get(id, CACHE_NAME, User.class);
        if (user == null) {
            log.info("查询功能，缓存未找到，直接读取数据库，ID为：" + id);
            Optional<User> optionalUser = userRepository.findById(id);

            if (optionalUser.isPresent()) {
                User user1 = optionalUser.get();
                cacheUtil.set(CACHE_NAME, id, user1, 10, 0);
                return user1;
            }
        }
        return user;
    }


    public Boolean delete(Integer id) {


        return cacheUtil.remove(id,CACHE_NAME);



    }

}
